from datetime import date, timedelta

from rest_framework.generics import ListAPIView, ListCreateAPIView
from rest_framework.views import APIView
from rest_framework.response import Response

from apps.goods.models import GoodsVisitCount
from apps.meiduo_admin.serializers.statistical import GoodCountSerializer
from apps.users.models import User

#############统计用户总数$#############
class UserTotalCountView(APIView):
    '''
    统计用户总数
    '''
    def get(self,request):
        # 1.查询用户获取用户总数
        count=User.objects.filter(is_staff=False).count()
        # 2.返回用户数量
        return Response({
            "count":count
        })

############日增用户统计###############
class UserDayCountView(APIView):
    def get(self,request):
    # 1.获取当天日期
        now_date = date.today()
        # 2.根据当天日期查询当天注册用户数量
        count = User.objects.filter(is_staff=False,
                                    date_joined__gte=now_date).count()
        # 3.返回注册用户数量结果
        return Response({
            "count":count,
            "date":now_date
        })

############日活用户统计###############
class UserCountView(APIView):
    def get(self,request):
    # 1.获取当天日期
        now_date = date.today()
        # 2.根据当天日期查询当天注册用户数量
        count = User.objects.filter(is_staff=False,
                                    last_login__gte=now_date).count()
        # 3.返回注册用户数量结果
        return Response({
            "count":count,

        })

############下单用户统计###############
class UserOrederCountView(APIView):
    def get(self,request):
    # 1.获取当天日期
        now_date = date.today()
        # 2.根据当天日期查询当天注册用户数量
        users = set(User.objects.filter(is_staff=False,
                                    orderinfo__create_time__gte=now_date))
        count = len(users)
        # 3.返回注册用户数量结果
        return Response({
            "count":count,
            "date":now_date

        })

############月增用户统计###############
class UserMonthCountView(APIView):
    def get(self, request):
        # 1.获取当天日期
        now_date = date.today()
        # 2.获取一个月之前的日期
        old_date = now_date - timedelta(30)
        # 3.查询一个月范围内的注册数量(循环遍历30次获取一个月内的数据)
        date_list=[]
        for i in range(30):
            # 当天日期
            index_date=old_date+timedelta(i)
            # 下一天日期
            next_date=old_date+timedelta(i+1)
            # 查询条件是大于当前日期index_date，小于明天日期的用户cur_date，得到当天用户量
            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=next_date).count()
            # 添加到列表
            date_list.append({
                "count":count,
                "date":index_date
            })
            # 4.返回一个月内用户注册数量
        return Response(date_list)

############日商品分类访问量统计#########
class GoodCountView(ListAPIView):
    # 指定序列化器
    serializer_class = GoodCountSerializer
    # 指定查询集
    queryset = GoodsVisitCount.objects.filter(date=date.today())

